package com.mymarkdown.app.service.impl;


import com.mymarkdown.app.common.lister.FileWatch;
import com.mymarkdown.app.factory.FileWatchFactory;
import com.mymarkdown.app.interfaces.ModifyWindow;
import com.mymarkdown.app.interfaces.UserInfoService;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author zenglun
 * @date 2021/12/15 9:11 上午
 * @description: TODO
 */
@Slf4j
public class DefaultUserOperationFileService extends AbstractUserOperationFileService {

    private ModifyWindow modifyWindow;

    private UserInfoService userInfoService;

    private FileWatch fileWatch;



    public DefaultUserOperationFileService(BlockingQueue<File> fileBlockingQueue, ModifyWindow modifyWindow, UserInfoService userInfoService) {
        super(fileBlockingQueue);
        this.modifyWindow = modifyWindow;
        this.userInfoService = userInfoService;
        this.fileWatch = FileWatchFactory.getFileWatch();
    }

    @Override
    public void put(File file) throws InterruptedException {
        try {
            this.fileBlockingQueue.put(file);
        } finally {
            this.modifyWindow.changeTitle();
            //启动文件系统监听器
            if (!this.fileWatch.isStart()){
                //设置监听的目录并启动文件监听器
                this.modifyWindow.loadWorkDirTree();
                this.fileWatch.addWatchPath(this.userInfoService.getWorkDir().getPath());
                this.fileWatch.start();
                log.info("[DefaultUserOperationFileService]---[put],文件监听程序已经启动...");
            }
        }
    }

    @Override
    public File take() throws InterruptedException {
        try {
            return this.fileBlockingQueue.take();
        } finally {
            this.modifyWindow.changeTitle();
        }
    }

    @Override
    public File poll(long timeout, TimeUnit unit) throws InterruptedException {
        return this.poll(timeout, unit);
    }

    @Override
    public File remove() {
        try {
            return this.fileBlockingQueue.remove();
        } finally {
            this.modifyWindow.changeTitle();
        }
    }

    @Override
    public File peek() {
        return this.fileBlockingQueue.peek();
    }

    @Override
    public int size() {
        return this.fileBlockingQueue.size();
    }

    @Override
    public boolean isEmpty() {
        return this.fileBlockingQueue.isEmpty();
    }

    @Override
    public void clear() {
        // 清除工作需要设置相关的操作
        this.fileBlockingQueue.clear();
        this.modifyWindow.changeTitle();
    }
}
